﻿using System;
using System.Windows.Forms;
using FastFood.Business.Entities;
using FastFood.Business.Logic;
using FastFood.Windows.Helpers;


namespace FastFood.Windows.Forms.Administracion.Comestibles
{
    public delegate void GetObjeto(object o );

    public partial class CwfInsumoBusqueda : UserControl
    {
        InsumosManager insumoManager;
        public event GetObjeto CwfInsumoBusqueda_SeleccionEntidad;

        public CwfInsumoBusqueda()
        {
            InitializeComponent();
            insumoManager = new InsumosManager();
        }

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            buscarInsumo();
        }

        private void btnLimpiar_Click(object sender, EventArgs e)
        {
            limpiar();
        }

        private void insumosDataGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
            {
                if (CwfInsumoBusqueda_SeleccionEntidad != null && insumosBindingSource.Current != null)
                    CwfInsumoBusqueda_SeleccionEntidad(insumosBindingSource.Current);
            }

        }

        private void buscarInsumo()
        {
            insumosBindingSource.DataSource = insumoManager.ListarByNombreOrUnidadAndVendible(txtNombre.Text, txtUnidades.Text, false);
        }

        public void limpiar()
        {
            txtNombre.Text = string.Empty;
            txtUnidades.Text = string.Empty;
            insumosBindingSource.Clear();
            txtNombre.Focus();
        }

        private void txtNombre_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down)
            {
                if (insumosBindingSource.Count > 0)
                {
                    insumosDataGridView.Focus();
                    insumosBindingSource.MoveFirst();
                }
            }

            else if (e.KeyCode == Keys.Enter)
            {
                if (insumosBindingSource.Count == 1)
                {
                    CwfInsumoBusqueda_SeleccionEntidad(insumosBindingSource.Current);
                }
            }
        }

        private void CwfInsumoBusqueda_Load(object sender, EventArgs e)
        {
            txtNombre.Focus();
        }

        private void insumosDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (CwfInsumoBusqueda_SeleccionEntidad != null && insumosBindingSource.Current != null)
                CwfInsumoBusqueda_SeleccionEntidad(insumosBindingSource.Current);
        }

        private void txtNombre_TextChanged(object sender, EventArgs e)
        {
            buscarInsumo();
        }
    }
}
